'''
Created on 2010-4-28

@author: Jeffrey
'''
from models import CoolCategory
from models import CoolTag
from models import CoolBookmark
import random
import re
import urllib
import zlib
from urllib import URLopener
from random import choice
from PNGCanvas import PNGCanvas
import md5

user_agents = [
    'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',
    'Opera/9.25 (Windows NT 5.1; U; en)',
    'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',
    'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',
    'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',
    'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9'
]

class MyOpener(URLopener, object):
    version = choice(user_agents)

def getBookmarksByOwner(user):
    bookmarks = CoolBookmark.all().filter("owner = ", user)
    return bookmarks

def getPublicBookmarks():
    bookmarks = CoolBookmark.all().filter("privilege = ", "public")
    return bookmarks

def saveTags(tags):
    taglist = split_tags(tags)
    for t in taglist:
        if CoolTag.all().filter('name = ', t).count() == 0:
            newtag = CoolTag()
            newtag.name = t
            newtag.tagindex = random.randint(1, 16)
            newtag.put()
    return taglist

def getImageByUpload(request):
    image = request.get("file")
    if image:
        mime = request.body_file.vars['file'].headers['content-type']
        if mime.find('image') == -1:
            image = None

        return image

def getImageByUrl(url):
    try:
        urlopen = urllib.URLopener()
        fp = urlopen.open('http://images.websnapr.com/?size=S&key=88275ImzxoSl&url=' + url)
        image = fp.read()
        fp.close()        
    except:
        image = None
        
    return image

def getContent(url):
    try:
        urlopen = MyOpener()
        fp = urlopen.open(url)
        content = fp.read()
        fp.close()
        content = zlib.compress(content, 9)
    except:
        content = None
        
    return content

def updateCategoryBookmarkCount(category):
    if category:
        bookmarkcount = CoolBookmark.all().filter('category = ', category).count()
        category.bookmarkcount = bookmarkcount
        category.put()

def split_tags(s):
    tags = list(set([t.strip() for t in re.split('[,;\\/\\\\]*', \
                s) if t != ''])) #uniq
    return tags

def getCheckCode():
    checkcode = random.randint(1000, 9999)
    return str(checkcode)

def getCheckCodeImage(checkcode, style = None):
 
    numbers = PNGCanvas(300, 30)
    
    urlopen = urllib.URLopener() 
    fp = urlopen.open('/numbers.png')   
    f = fp.read()
    numbers.load(f)
    fp.close()
    
    if numbers:
        output = PNGCanvas(120, 30)
        for i in range (0, 4):
            r = checkcode[i]
            numbers.copyRect(r * 30 + 1, 1, (r + 1) * 30 - 1, 29, i * 30 + 1, 1, output)
        return output.dump()
    else:
        return None

class Image():
    text = None
    md5Text = None
    img = None
    width = 0
    height = 0
    textX = 10
    textY = 10
    beginX = 5
    endX = 5
    beginY = 5
    endY = 5
    spare = 4

    def __init__(self,text=None):
        if(text==None):
            self.text = self.getRandom()
        else:
            self.text = text
        #self.getMd5Text()
        self.width = len(str(self.text))*(self.spare+self.textX)+self.beginX+self.endX
        self.height = self.textY + self.beginY + self.endY

    def create(self):
        self.img = PNGCanvas(self.width,self.height)
        self.img.color = [0xff,0xff,0xff,0xff]
        #self.img.color = [0x39,0x9e,0xff,0xff]
        #self.img.verticalGradient(1,1,self.width-2, self.height-2,[0xff,0,0,0xff],[0x60,0,0xff,0x80])
        self.img.verticalGradient(1,1,self.width-2, self.height-2,[0xff,0,0,0xff],[0x20,0,0xff,0x80])

        for i in range(4):
            a = str(self.text)[i]
            self.writeText(a,i)
        
        for i in range(300):
            x = random.randrange(1,self.width)
            y = random.randrange(1,self.height)
            self.img.point(x, y, [0xC0, 0xC0, 0xC0, 0xff])

        return self.img.dump()

    def getRandom(self):
        intRand = random.randrange(1000,9999)
        return intRand

    def getMd5Text(self):
        m = md5.new()
        m.update(str(self.text))
        self.md5Text = m.hexdigest()

    def writeText(self,text,pos=0):
        if(text=="1"):
            self.writeLine(pos, "avc")
        elif(text=="2"):
            self.writeLine(pos, "aht")
            self.writeLine(pos, "hvtr")
            self.writeLine(pos, "ahc")
            self.writeLine(pos, "hvbl")
            self.writeLine(pos, "ahb")
        elif(text=="3"):
            self.writeLine(pos, "aht")
            self.writeLine(pos, "ahc")
            self.writeLine(pos, "ahb")
            self.writeLine(pos, "avr")
        elif(text=="4"):
            self.writeLine(pos, "hvtl")
            self.writeLine(pos, "ahc")
            self.writeLine(pos, "avc")
        elif(text=="5"):
            self.writeLine(pos, "aht")
            self.writeLine(pos, "hvtl")
            self.writeLine(pos, "ahc")
            self.writeLine(pos, "hvbr")
            self.writeLine(pos, "ahb")
        elif(text=="6"):
            self.writeLine(pos, "aht")
            self.writeLine(pos, "avl")
            self.writeLine(pos, "ahc")
            self.writeLine(pos, "hvbr")
            self.writeLine(pos, "ahb")
        elif(text=="7"):
            self.writeLine(pos, "aht")
            self.writeLine(pos, "avr")
        elif(text=="8"):
            self.writeLine(pos, "aht")
            self.writeLine(pos, "avl")
            self.writeLine(pos, "ahc")
            self.writeLine(pos, "avr")
            self.writeLine(pos, "ahb")
        elif(text=="9"):
            self.writeLine(pos, "aht")
            self.writeLine(pos, "avr")
            self.writeLine(pos, "ahc")
            self.writeLine(pos, "ahb")
            self.writeLine(pos, "hvtl")
        elif(text=="0"):
            self.writeLine(pos, "aht")
            self.writeLine(pos, "avl")
            self.writeLine(pos, "avr")
            self.writeLine(pos, "ahb")


    def writeLine(self,pos,type):
        if(type=="avl"):
            self.img.line(
                          self.beginX+(self.textX+self.spare)*pos,
                          self.beginY,
                          self.beginX+(self.textX+self.spare)*pos,
                          self.beginY+self.textY
                          )
        elif(type=="avc"):
            self.img.line(
                          self.beginX+(self.textX+self.spare)*pos+self.textX/2,
                          self.beginY,
                          self.beginX+(self.textX+self.spare)*pos+self.textX/2,
                          self.beginY+self.textY
                          )
        elif(type=="avr"):
            self.img.line(
                          self.beginX+(self.textX+self.spare)*pos+self.textX,
                          self.beginY,
                          self.beginX+(self.textX+self.spare)*pos+self.textX,
                          self.beginY+self.textY
                          )
        elif(type=="aht"):
            self.img.line(
                          self.beginX+(self.textX+self.spare)*pos,
                          self.beginY,
                          self.beginX+(self.textX+self.spare)*pos+self.textX,
                          self.beginY,
                          )
        elif(type=="ahc"):
            self.img.line(
                          self.beginX+(self.textX+self.spare)*pos,
                          self.beginY+self.textY/2,
                          self.beginX+(self.textX+self.spare)*pos+self.textX,
                          self.beginY+self.textY/2
                          )
        elif(type=="ahb"):
            self.img.line(
                          self.beginX+(self.textX+self.spare)*pos,
                          self.beginY+self.textY,
                          self.beginX+(self.textX+self.spare)*pos+self.textX,
                          self.beginY+self.textY
                          )
        elif(type=="hvtl"):
            self.img.line(
                          self.beginX+(self.textX+self.spare)*pos,
                          self.beginY,
                          self.beginX+(self.textX+self.spare)*pos,
                          self.beginY+self.textY/2
                          )
        elif(type=="hvtr"):
            self.img.line(
                          self.beginX+(self.textX+self.spare)*pos+self.textX,
                          self.beginY,
                          self.beginX+(self.textX+self.spare)*pos+self.textX,
                          self.beginY+self.textY/2
                          )
        elif(type=="hvbl"):
            self.img.line(
                          self.beginX+(self.textX+self.spare)*pos,
                          self.beginY+self.textY/2,
                          self.beginX+(self.textX+self.spare)*pos,
                          self.beginY+self.textY
                          )
        elif(type=="hvbr"):
            self.img.line(
                          self.beginX+(self.textX+self.spare)*pos+self.textX,
                          self.beginY+self.textY/2,
                          self.beginX+(self.textX+self.spare)*pos+self.textX,
                          self.beginY+self.textY
                          )

